package com.klikmee.sms.chat.web.filters;

import java.text.MessageFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.klikmee.sms.cef.services.Service;
import com.klikmee.sms.chat.web.dao.SubscriberDAO;
import com.klikmee.sms.services.chat.model.Question;

public class SessionFilterImpl extends AbstractFilter {

	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(SessionFilterImpl.class);

	/**
	 * Charging settings
	 */
	private Long serviceId = null;
	private Long chargingId = null;

	/**
	 * Instance of {@link SubscriberDAO} used to query subscribers
	 */
	private SubscriberDAO subscriberDAO = null;

	private String subscriptionInfoText;
	
	/**
	 * Number of days to keep session idle. After this period subscriber will be marked as inactive.
	 */
	private Long sessionValidityPeriod = null;

	/**
	 * <p>
	 * This filter is activated on every message. It looks for the subscriber in data base and if it's not found it sends an info message to the subscriber, informing him of the necessity of
	 * subscription.
	 * </p>
	 * 
	 * @return true if filter was activated, false otherwise
	 */
	@Override
	public boolean processMessage(Question question) {

		// check if user has an active session
		boolean hasActiveSession = subscriberDAO.checkIfHasActiveSessionAndUpdate(question.getFromNumber());
		if (!hasActiveSession) {
			// inform the user that he must register for the service first
			Long responseCoreId = coreAdapter.sendMessage(chargingId, serviceId, Service.SERVICE_FLAG_SEMANTIC_OK, question.getCoreID(), subscriptionInfoText);
			persistAnswer(question, subscriptionInfoText, responseCoreId, false);

			question.setVisable(false);
			questionDAO.edit(question);
			
			logger.info(MessageFormat.format("Session filter activation for msisdn [{0}]", question.getFromNumber()));
			return true;
		}

		return false;
	}
	
	/**
	 * <p>
	 * Disables subscriptions which did not have any activity in last {@link #sessionValidityPeriod} days. 
	 * </p> 
	 */
	public void disableExpiredSessions(){
		Date currentTime = new Date();
		long sessionValiditiPeriod = 1000 * 60 * 60 * 24 * sessionValidityPeriod;
		long timeDifference = currentTime.getTime() - sessionValiditiPeriod;
		Date validityDate = new Date(timeDifference);
		
		int numOfDisabledSessions = subscriberDAO.disableExpiredSubscriptions(validityDate);
		logger.info(MessageFormat.format("Disabled [{0}] sessions.", numOfDisabledSessions));
	}
	
	public void setServiceId(Long serviceId) {
		this.serviceId = serviceId;
	}

	public void setChargingId(Long chargingId) {
		this.chargingId = chargingId;
	}

	public void setSubscriberDAO(SubscriberDAO subscriberDAO) {
		this.subscriberDAO = subscriberDAO;
	}

	public void setSubscriptionInfoText(String subscriptionInfoText) {
		this.subscriptionInfoText = subscriptionInfoText;
	}

	public void setSessionValidityPeriod(Long sessionValidityPeriod) {
		this.sessionValidityPeriod = sessionValidityPeriod;
	}
}
